package sz.szsmk.citizencard.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.chenenyu.router.Router;
import com.chenenyu.router.annotation.Route;

import org.jetbrains.annotations.NotNull;

import retrofit.BaseUrl;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.FogetGetcodeActivityBinding;
import sz.szsmk.citizencard.dialog.TwoButtonDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CheckThirdAppRes;
import sz.szsmk.citizencard.model.network.bean.response.ImgCodeRes;
import sz.szsmk.citizencard.model.network.bean.response.ProtocolsRes;
import sz.szsmk.citizencard.mvp.contract.IGetCodeContact;
import sz.szsmk.citizencard.mvp.presenter.GetcodePresenter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.ui.dialogs.VerifyCodeDialog;
import sz.szsmk.citizencard.ui.dialogs.WalletAuthDialogNew;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.util.zxyh.CheckContentUtil;
import sz.szsmk.citizencard.widget.NoLineClickSpan;
import sz.szsmk.citizencard.widget.NoLinedClickSpan;
import sz.szsmk.citizencard.widget.PureTextWebViewActivity;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/5/31 10:31
 * description:
 */
@Route("getcode")
public class GetCodeActivty extends IBaseActivity<GetcodePresenter, FogetGetcodeActivityBinding>
        implements IGetCodeContact.IGetCodeView, View.OnClickListener {

    private String type;
    //    private String login_type;
    private String userPhone;
    private String codeType;
    private String androidId;
    private String login_type;

    @Override
    protected int attachLayoutRes() {
        return R.layout.foget_getcode_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder()
                .appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        login_type = ACache.get(DaggerApplication.getIns()).getAsString("login_type");
        androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        type = getIntent().getStringExtra("type");
        mPresenter.getProtocols("zhsz_app_zhuce");
        Log.d("clark",AndroidUtils.getVersionName());
        if (type.equals("forget")) {
            dataBinding.getcodeXy.setVisibility(View.GONE);
            CheckContentUtil.checkContent(GetCodeActivty.this,dataBinding.forgetGetCode,dataBinding.loginUserEt);
            dataBinding.loginUserEt.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    CheckContentUtil.checkPhoneContent(GetCodeActivty.this,dataBinding.forgetGetCode,dataBinding.loginUserEt);
                }
            });
        }
        if (type.equals("regitst")) {
            dataBinding.getcodeXy.setVisibility(View.VISIBLE);
            CheckContentUtil.checkBoxContent(GetCodeActivty.this,dataBinding.forgetGetCode,dataBinding.cbAgreement,dataBinding.loginUserEt);
            dataBinding.loginUserEt.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    CheckContentUtil.checkPhoneCheckContent(GetCodeActivty.this,dataBinding.forgetGetCode,dataBinding.cbAgreement,dataBinding.loginUserEt);
                }
            });
            dataBinding.cbAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    CheckContentUtil.checkPhoneCheckContent(GetCodeActivty.this,dataBinding.forgetGetCode,dataBinding.cbAgreement,dataBinding.loginUserEt);
                }
            });
        }
        if (type.equals("modifyPhone")) {

        }
        dataBinding.titleLayout.back.setOnClickListener(this);
        dataBinding.forgetGetCode.setOnClickListener(this);
        dataBinding.getcodeAgreement.setOnClickListener(this);
        dataBinding.tvAuthAgreement.setOnClickListener(this);
        dataBinding.getcodeAgreement.setOnClickListener(this);

    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.getcode_agreement) {//                Bundle bundle = new Bundle();
//                bundle.putString("isNeedGetPermission","1");
//                bundle.putString("url", Constant.BASE_URL + "app-front-end/#/common/serviceAgreement");
//                Intent intent = new Intent(GetCodeActivty.this, PureTextWebViewActivity.class);
//                intent.putExtra("url",Constant.BASE_URL + "app-front-end/#/common/serviceAgreement");
//                intent.putExtra("isNeedGetPermission","1");
//                Constant.isOpenPer=true;
//                startActivity(intent);

            //JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
        } else if (id == R.id.tv_authAgreement) {//                Bundle bundle1 = new Bundle();
//                bundle1.putBoolean("isNeedGetPermission",true);
//                bundle1.putString("url", Constant.BASE_URL + "app-front-end/#/common/secretAgreement");
//                JumpUtils.jumptoNatvie(this, "webView", 0, bundle1);
        } else if (id == R.id.forget_get_code) {
            userPhone = dataBinding.loginUserEt.getText().toString();
            if (userPhone == null || userPhone.length() == 0 || userPhone.isEmpty()) {
                Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (dataBinding.protocols.getText().toString().contains("获取协议中") || dataBinding.protocols.getText().toString().contains("获取协议失败")) {
                Toast.makeText(this, getResources().getString(R.string.get_protocols_fail), Toast.LENGTH_SHORT).show();
                return;
            }

            if (dataBinding.getcodeXy.getVisibility() == View.VISIBLE) {
                if (!dataBinding.cbAgreement.isChecked()) {
                    Toast.makeText(this, "请先勾选用户注册协议", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            boolean isPhone = StringUtils.isPhone(userPhone);
            if (!isPhone) {
//                    PubUtils.popTipOrWarn(this, "请输入一个正确的手机号");
                return;
            }
            if (type.equals("regitst")) {
                codeType = "1";
            }
            if (type.equals("forget")) {
                codeType = "2";
            }
            if (type.equals("modifyPhone")) {
                codeType = "4";
            }
            if (login_type != null) {
                Log.d("clark", "" + login_type + "--" + codeType);
                codeType = "1";
//                    mPresenter.getImgCode(userPhone);
                //获取弹窗信息 获取成功之后显示

                //显示弹窗

//                    mPresenter.sendGetcodeRequest(androidId, codeType, userPhone);
                mPresenter.checkUserByMobile(type, androidId, codeType, userPhone);
//                    mPresenter.checkThirdApp(userPhone);
            } else {
                Log.d("clark", "22220---" + login_type + "--" + codeType);

                //显示弹窗
//                    mPresenter.getImgCode(userPhone);
                mPresenter.checkUserByMobile(type, androidId, codeType, userPhone);
            }
        }
    }


    @Override
    public void updataError(String message) {

    }

    @Override
    public void updataSuccess() {

        Router.build("checkCode")
                .with("type", type)
                .with("userPhone", userPhone)
                .with("codeType", codeType)
                .go(this);
        finish();
    }

    @Override
    public void getCodeFail(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
//        Router.build("checkCode")
//                .with("type", type)
//                .with("userPhone", userPhone)
//                .with("codeType", codeType)
//                .go(this);
//        finish();
    }

    @Override
    public void checkUserSucc(String msg) {


    }

    @Override
    public void checkUserFail(BaseBean msg) {
        Toast.makeText(this, msg.getMessage(), Toast.LENGTH_SHORT).show();
        if (type.equals("forget")) {
            codeType = "2";
            if (msg.getCode().equals("000001")) {
                Router.build("checkCode")
                        .with("type", type)
                        .with("userPhone", userPhone)
                        .with("codeType", codeType)
                        .go(this);
                finish();
            } else {
//                PubUtils.popTipOrWarn(this, msg.getMessage());
            }

        }

    }

    @Override
    public void getCodeSucc() {
        Router.build("checkCode")
                .with("type", type)
                .with("userPhone", userPhone)
                .with("codeType", codeType)
                .go(this);
        finish();
    }

    @Override
    public void thirdAppLogin() {
        String login_type = ACache.get(this).getAsString("login_type");

        int i = Integer.parseInt(login_type);
        String uid = ACache.get(this).getAsString("uid");
        mPresenter.thirdAppLogin(i, userPhone, androidId, uid);

    }

    @Override
    public void thirdAppLoginSucc() {
        Router.build("main")
                .go(this);
    }

    @Override
    public void thirdAppLoginFail(String message) {

    }

    @Override
    public void checkThirdAppFail() {

    }

    @Override
    public void checkThirdAppSucc(CheckThirdAppRes response) {
        String checkStatus = response.getCheckStatus();
        if (checkStatus.equals("1")) {
            //存在 直接登录

            String login_type = ACache.get(this).getAsString("login_type");

            int i = Integer.parseInt(login_type);
            String uid = ACache.get(this).getAsString("uid");
            //掉接口


//            mPresenter.thirdAppLogin(i, userPhone, androidId, uid);
        } else {
            //不存在 发送验证码
            mPresenter.getImgCode(userPhone);
//            mPresenter.sendGetcodeRequest(androidId, codeType, userPhone);
        }
    }

    @Override
    public void serviceAgreementFail() {

    }

    @Override
    public void serviceAgreementSucc() {

    }

    @Override
    public void userIshave() {
        showDelDialog();
    }

    @Override
    public void getProtocolsSucc(ProtocolsRes protocolsRes) {
        //获取协议成功，写入到页面
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView protocolText = dataBinding.protocols;
                if(protocolsRes.getUserAppAgreementDtos().size()==0){
                    Toast.makeText(GetCodeActivty.this,getResources().getString(R.string.get_protocols_fail),Toast.LENGTH_LONG).show();
                    return;
                }
                protocolText.setText(getResources().getString(R.string.registerAndAgree));
                for (int i = 0; i < protocolsRes.getUserAppAgreementDtos().size(); i++) {
                    SpannableString spStr;
                    if (protocolsRes.getUserAppAgreementDtos().size()> 1 && i == protocolsRes.getUserAppAgreementDtos().size() - 1) {
                        //最后一个协议增加一个"和"字 重新赋值
                        spStr = new SpannableString("和" + protocolsRes.getUserAppAgreementDtos().get(i).getAgreementName());
                        String protocol = protocolsRes.getUserAppAgreementDtos().get(i).getAgreementName();
                        NoLinedClickSpan clickSpan = new NoLinedClickSpan("#2184FA", protocolsRes.getUserAppAgreementDtos().get(i).getH5Url(), GetCodeActivty.this);
                        spStr.setSpan(clickSpan, 1, protocol.length()+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        protocolText.append(spStr);
                    } else {
                        spStr = new SpannableString(protocolsRes.getUserAppAgreementDtos().get(i).getAgreementName());
                        String protocol = protocolsRes.getUserAppAgreementDtos().get(i).getAgreementName();
                        NoLinedClickSpan clickSpan = new NoLinedClickSpan("#2184FA", protocolsRes.getUserAppAgreementDtos().get(i).getH5Url(), GetCodeActivty.this);
                        spStr.setSpan(clickSpan, 0, protocol.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        protocolText.append(spStr);
                    }


                }
//        protocolText.append(String.format(getResources().getString(R.string.dialog_tips_end), "APP"));
                protocolText.setMovementMethod(LinkMovementMethod.getInstance());
            }
        });

    }

    @Override
    public void getProtocolsFail() { //获取版本数据的异常处理
        Toast.makeText(this, getResources().getString(R.string.get_protocols_fail), Toast.LENGTH_SHORT).show();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dataBinding.protocols.setText("获取协议失败");
            }
        });
    }

    VerifyCodeDialog verifyCodeDialog;

    @Override
    public void getImgCodeSucc(ImgCodeRes imgCodeRes) {
        if (verifyCodeDialog!=null&&verifyCodeDialog.isShowing()) {
            verifyCodeDialog.update(Constant.BASE_URL + imgCodeRes.getImgUrl());
        } else {
            verifyCodeDialog = new VerifyCodeDialog(this, userPhone, Constant.BASE_URL + imgCodeRes.getImgUrl());
            verifyCodeDialog.show();
            verifyCodeDialog.setCancelable(false);
            verifyCodeDialog.setIVerifyCodeDialogNew(new VerifyCodeDialog.IVerifyCodeDialog() {
                @Override
                public void onclick(@NotNull String phone, @NotNull String code) {
                   //验证验证码请求发出 在获取短信里面去验证验证码
                    mPresenter.sendGetcodeRequest(code,androidId, codeType, userPhone);
                }

                @Override
                public void refresh(@NotNull String phone) {
                    //刷新验证码
                    mPresenter.getImgCode(phone);
                }
            });
        }


    }

    @Override
    public void getImgCodeFail() {
        Toast.makeText(GetCodeActivty.this, "获取图片验证码失败，请稍后重新获取", Toast.LENGTH_SHORT).show();
    }

    private void showDelDialog() {
        final TwoButtonDialog dialog = new TwoButtonDialog(this, "用户已存在是否登录");
        dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {
                dialog.cancel();
            }
        });
        dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
//                balanceDaoDao.deleteAll();
                dialog.cancel();
                finish();

//                reFreshData();
            }
        });
        dialog.show();
    }

}
